from sqlalchemy.orm import Session
from typing import List, Optional, Union, Tuple

from deepinsight.stores.postgresql.repositories.base_repository import BaseRepository
from deepinsight.stores.postgresql.schemas.conversation import Conversation


class ConversationRepository(BaseRepository[Conversation]):
    """对话数据访问类"""

    def __init__(self, db: Session):
        """初始化对话仓库"""
        super().__init__(db, Conversation)

    def get_by_id(self, conversation_id: str) -> Optional[Conversation]:
        """
        根据对话ID获取对话

        :param conversation_id: 对话ID
        :return: 找到的对话或None
        """
        return self.db.query(Conversation).filter(Conversation.conversation_id == conversation_id).first()

    def get_by_user_id(self, user_id: str, offset: int = 0, limit: int = 100) -> List[Conversation]:
        """
        根据用户ID获取对话列表

        :param user_id: 用户ID
        :param offset: 跳过的记录数
        :param limit: 最大返回记录数
        :return: 对话列表
        """
        return self.db.query(Conversation) \
            .filter(Conversation.user_id == user_id) \
            .order_by(Conversation.created_time.desc()) \
            .offset(offset) \
            .limit(limit) \
            .all()

    def get_active_by_user_id(self, user_id: str) -> List[Conversation]:
        """
        获取用户的活跃对话

        :param user_id: 用户ID
        :return: 活跃对话列表
        """
        return self.db.query(Conversation) \
            .filter(
            Conversation.user_id == user_id,
            Conversation.status == "active"
        ) \
            .order_by(Conversation.created_time.desc()) \
            .all()

    def update_status(self, conversation_id: str, status: str) -> Optional[Conversation]:
        """
        更新对话状态

        :param conversation_id: 对话ID
        :param status: 新状态
        :return: 更新后的对话或None
        """
        conversation = self.get_by_id(conversation_id)
        if conversation:
            conversation.status = status
            self.db.commit()
            self.db.refresh(conversation)
        return conversation

    def update_title(self, conversation_id: str, new_title: str) -> tuple[Conversation, bool] | tuple[None, bool]:
        """
        更新title 内容

        :param conversation_id: 对话ID
        :param new_title: 新状态
        :return: 更新后的对话或None
        """
        conversation = self.get_by_id(conversation_id)
        if conversation:
            conversation.title = new_title
            self.db.commit()
            self.db.refresh(conversation)
            return conversation, True
        else:
            return None, False

    def delete_conversation(self, conversation_id: str) -> bool:
        """
        删除指定对话及其所有关联记录
        依赖数据库外键 ON DELETE CASCADE 自动清理 message/report

        :param conversation_id: 对话ID
        :return: True 删除成功；False 未找到该对话
        """

        conversation = self.get_by_id(conversation_id)
        if not conversation:
            return False

        self.db.delete(conversation)
        self.db.commit()
        return True

    def create_conversation(self, user_id, title, conversation_id) -> Conversation:
        """
        创建一条新的对话记录

        :param user_id: 用户id
        :param title: 会话题目
        :return: 已提交到数据库的 Conversation 实例
        """
        # 1. 创建 ORM 实例
        new_convo = Conversation(user_id=user_id, title=title, conversation_id=conversation_id)

        # 2. 加入会话
        self.db.add(new_convo)

        # 3. 立即提交（如需手动控制事务，可把 commit 放到外层）
        self.db.commit()

        # 4. 刷新以便拿到数据库生成的默认值/自增 ID
        self.db.refresh(new_convo)

        return new_convo